﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace BlockOS
{
    /// <summary>
    /// a LRU Chunk Storage.
    /// </summary>
    public class ChunkDataStorage
    {
        private Dictionary<Vector3Int, Entry> chunks = new();
        private readonly int maxChunkCount;
        private int useCounter = 0;

        public ChunkDataStorage(int maxChunkCount)
        {
            this.maxChunkCount = maxChunkCount;
        }

        public bool Contains(int x, int y, int z) => chunks.ContainsKey(new Vector3Int(x, y, z));

        public void AddChunkData(int x, int y, int z, ChunkData data)
        {
            if (chunks.Count > maxChunkCount)
            {
                var positions = chunks
                    .OrderBy(e => e.Value.recentUseTime)
                    .Take(chunks.Count - maxChunkCount)
                    .Select(e => e.Key)
                    .ToArray();
                foreach (var pos in positions)
                {
                    chunks.Remove(pos);
                }
            }
            chunks.Add(new Vector3Int(x, y, z), new Entry { data = data, recentUseTime = 0 });
        }

        public ChunkData GetChunkData(int x, int y, int z)
        {
            var result = chunks[new Vector3Int(x, y, z)];
            result.recentUseTime = useCounter++;
            return result.data;
        }

        private class Entry
        {
            public ChunkData data;
            public int recentUseTime;
        }
    }
}
